﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.Net;
using System.IO;
using System.Text;

namespace DailyMotion.DataAccess
{
    public class DMHelper
    {
      
        const string ChannelsUrl = "https://api.dailymotion.com/channels?sort=popular";
        const string VidoesByChannelFormatString = "https://api.dailymotion.com/channel/{0}/videos?fields=tags,views_last_week,embed_html,owner.avatar_medium_url,rating,ratings_total,thumbnail_large_url,owner,description,id,tags,title,thumbnail_url&sort=visited-today&page={1}&limit={2}";
        public const int DEFAULT_PAGE_SIZE = 20;
        public static DailyMotionPagedResult GetMainChannels()
        {

            HttpWebRequest request = WebRequest.Create(ChannelsUrl) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string answer = new StreamReader(response.GetResponseStream()).ReadToEnd();

            response.Close();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DailyMotionPagedResult));

            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(answer));
            DailyMotionPagedResult result = serializer.ReadObject(ms) as DailyMotionPagedResult;
            return result;
        }

        public static DailyMotionVideosPagedResult GetVideosByChannelId(string channelId, int pageNumber, int pageSize)
        {
            string url = string.Format(VidoesByChannelFormatString, channelId, pageNumber, pageSize);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string answer = new StreamReader(response.GetResponseStream()).ReadToEnd();

            response.Close();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DailyMotionVideosPagedResult));

            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(answer));
            DailyMotionVideosPagedResult result = serializer.ReadObject(ms) as DailyMotionVideosPagedResult;
            return result;
        }
    }


}
